package com.kdd.campus.sh.component;

import com.kdd.campus.common.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.kdd.campus.sh.util.JwtTokenUtil;
/**
 * JWT登录授权过滤器
 * Created by macro on 2018/4/26.
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        //1. 从请求头中获取token
        String token = request.getHeader(tokenHeader);
        if (token!=null && token.startsWith(tokenHead)){
            //2. 获取token中Bearer 后面的内容
            String authToken = token.substring(tokenHead.length()+1);
            //3. 从Redis中获取userId（key: token  value: userId）
            Object userId =  RedisUtil.get(authToken);
            //4. 如果token在Redis中不存在，表示token无效，验证失败
            if (userId==null) return;

            //5. 从token中获取用户信息
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            LOGGER.info("checking receiverName:{}", username);

            //6. 将用户信息封装成UsernamePasswordAuthenticationToken
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));//暂时还没用到权限，先简单封装

            //7. 将UsernamePasswordAuthenticationToken存入SpringSecurity上下文中
//            AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles())
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }
        // 通过验证
        chain.doFilter(request, response);
    }
}
